var Movie =require('../models/movie')
var Category=require('../models/category')
//index page
exports.index=function(req,res){
	Category
	.find({})
	.populate({path:'movies',options:{limit: 5}})
	.exec(function(err,categories){
		if (err) {
			console.log(err)
		}

		res.render('index',{
		title:'imooc 首页',
		categories:categories
		})
	})
	
}

exports.search=function(req,res){
	var catId = req.query.catid;
	var q=req.query.q;
	var page = parseInt(req.query.p,10)|| 0;//必须加类转换，results页面有判断语句，不转就不能比较
	var count=2
	var index = page *count;//每页展示2条数据
	
	if (catId) {
		Category
		.find({_id:catId})
		.populate({
			path:'movies',//这里populate其实实现的就是关系型数据库通过外键实现的join功能
			select:'title poster',
			//options:{limit: 2,skip: index}//skip跳过指定数量的数据，limit读取指定数量的数据;其实目前这样是可以分页的；但是视频中老师那边却是不可以的
		})
		.exec(function(err,categories){
			if (err) {
				console.log(err)
			}

			var category = categories[0] || {}
			var movies =category.movies
			var results = movies.slice(index,index+count)

			res.render('results',{
			title:'imooc 结果列表页面',
			keyword:category.name,
			currentPage:(page+1),
			query:'catid='+catId,
			totalPage:Math.ceil(movies.length/count),
			movies:results
			})
		})
	}else{
		Movie
		.find({title:new RegExp(q+'.*')})//正则实现模糊搜索
		.exec(function(err,movies){
			if(err){
				console.log(err)
			}

			var results = movies.slice(index,index+count)
			res.render('results',{
				title:'imooc 结果列表页面',
				keyword:q,
				currentPage:(page+1),
				query:'q='+q,
				totalPage:Math.ceil(movies.length/count),
				movies:results
			})
		})
	}
}

	